package kaalanshare;

import java.io.*;
import java.net.Socket;
import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * User: twin
 * Date: 23.04.12
 * Time: 14:16
 * To change this template use File | Settings | File Templates.
 */
public class SenderFileRunnable implements Runnable {
    private Socket socket = null;

    SenderFileRunnable(Socket socket) {
        this.socket = socket;
    }

    public static void dataOutputStreamWrite(Socket sock, String filename) throws IOException {
        File myFile = new File("share/" + filename);
        byte[] mybytearray = new byte[(int) myFile.length()];

        FileInputStream fis = new FileInputStream(myFile);
        BufferedInputStream bis = new BufferedInputStream(fis);

        DataInputStream dis = new DataInputStream(bis);
        dis.readFully(mybytearray, 0, mybytearray.length);

        OutputStream os = sock.getOutputStream();

        //Sending file name and file size to the server
        DataOutputStream dos = new DataOutputStream(os);

        // send filename
        dos.writeUTF(filename);
        System.out.println(filename);
        //send filesize
        dos.writeLong(mybytearray.length);
        System.out.println(mybytearray.length);
        //send file
        dos.write(mybytearray, 0, mybytearray.length);
        dos.flush();
    }


    public void run() {

        try {
            System.out.println("starting sending");
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            //reading requested filename
            String requestedFile = in.readUTF();
            System.out.println(requestedFile);
            LinkedList<String> list = null;
            synchronized (Main.class) {
                //getting list of files in folder or the same file
                list = Main.folder.getFolderStructByUrl(requestedFile);
            }
            if (list.isEmpty()) {
                out.writeUTF("!!no_File");
                out.flush();
            } else {
                for (String fullFileName : list) {
                    System.out.println(fullFileName);
                    //sending files
                    dataOutputStreamWrite(socket, fullFileName);
                }
                System.out.println("finished");
                out.writeUTF("!!finished");
                out.flush();
            }
            System.out.println("finished sending");
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
}
